#ifndef __TCPCONNECTION_H__
#define __TCPCONNECTION_H__

#include "Socket.h"
#include "SocketIO.h"
#include "InetAddress.h"
#include <functional>
#include <memory>

using std::shared_ptr;

namespace myNameSpace {
class EventLoop;
class TLV;
class TcpConnection: public std::enable_shared_from_this<TcpConnection> { // 继承std::enable_shared_from_this
public:
    using TcpConnectionCallback = std::function<void(shared_ptr<TcpConnection>)>;

    TcpConnection(int connectFd, EventLoop *pEventLoop);

    void send(const string &msg);
    void sendTLV(const TLV &tlv);
    string receive();
    int readPacket(Packet &packet);

    string getConnectionInfo() const;
    bool isClosed() const;
    void shutdown();

    void setNewConnectionCallback(TcpConnectionCallback &cb);
    void setMessageCallback(TcpConnectionCallback &cb);
    void setCloseCallback(TcpConnectionCallback &cb);

    void handleNewConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();

    void notifyEventLoopToSendResponse(const string &response);
    void sendInLoop(const TLV &response);

private:
    InetAddress getLocalAddr() const;
    InetAddress getPeerAddr() const;

private:
    Socket _connectSock;
    SocketIO _sockIO;
    InetAddress _localAddr;
    InetAddress _peerAddr;
    EventLoop *_pEventLoop;
    TcpConnectionCallback _onNewConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;
};
} // end of namespace myNameSpace

#endif
